package com.example.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.example.database.DbManager;
import com.example.juyixia.Activity_chatActivity;
import com.example.juyixia.Chat_Fragment;
import com.example.juyixia.MainActivity;
import com.example.juyixia.R;
import com.example.mathutil.RSACoder;
import com.exanple.data.Activeinfo;
import com.exanple.data.ChatMsgEntity;
import com.exanple.data.Messageinfo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import sun.misc.BASE64Decoder;

public class RecmessService extends Service {
	private boolean isRun;// 线程是否继续的标志
	private Handler handler1; // 显示当前时间线程消息处理器。
	public static final String bm = "utf-8";
	private DbManager mgr;
	private ChatMsgEntity recmess;
	private String privatekey;
	private String currentusername;
	 private Handler handler2;// 推送通知栏消息的线程消息处理器
		private SQLiteDatabase db;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		 final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// 注册通知管理器  
		 db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);
			db.execSQL("CREATE TABLE IF NOT EXISTS pendmessage" +  
	                "(id INTEGER PRIMARY KEY AUTOINCREMENT, sendname VARCHAR,recname VARCHAR,content VARCHAE,time VARCHAR)");
		mgr = new DbManager(this);
		isRun=true;
		privatekey=intent.getStringExtra("privatekey");
		currentusername=intent.getStringExtra("username");
		 new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Intent intent=new Intent();
						intent.setAction(Activity_chatActivity.ACTION_UPDATEUI);
						Intent intent1=new Intent();
						intent1.setAction("fragment.action.service"); 
						ServerSocket serverSocket = new ServerSocket(36363);
						while (isRun) {
							Socket client = serverSocket.accept();
							BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), bm));
							String str = in.readLine();
							JSONObject recmessjson =new JSONObject(str);
							JSONTokener messParser = new JSONTokener(recmessjson.toString()); 
							 JSONObject messagejson = (JSONObject) messParser.nextValue();
							 String encryword=messagejson.getString("消息内容");

							 	BASE64Decoder dec=new BASE64Decoder();
							 		byte[]after=null;	
							 		after =dec.decodeBuffer(encryword);//使用BASE64解码
						       byte[] decode=RSACoder.decryptByPrivateKey(after, privatekey);
							 recmess=new ChatMsgEntity(messagejson.getString("发送人"),messagejson.getString("接收人"),messagejson.getString("发送时间"),new String(decode));
							 if(messagejson.getString("接收人").equals(currentusername)){
							 for (Messageinfo mess : Messageinfo.messlist) {
								if(mess.getSendname().equals(messagejson.getString("发送人"))){
									Messageinfo.messlist.remove(mess);
									
								}
							}
							
                              Messageinfo.messlist.add(new Messageinfo(messagejson.getString("发送人"),messagejson.getString("接收人"),new  String(decode), messagejson.getString("发送时间"),messagejson.getString("publickey"),messagejson.getString("ip")));
							 }
							
							mgr.add(recmess);

							 sendBroadcast(intent);  
							 sendBroadcast(intent1);
							Message msg = new Message();
							handler2.sendMessage(msg);
						}
					}catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 

				}
			}).start();// 默认线程不启动，必须自己start()
		 handler1 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了
				@Override
				public boolean handleMessage(Message msg) {
					try {
						Toast.makeText(getApplicationContext(), "您收到"+recmess.getSendname()+"发来的新消息！",
							     Toast.LENGTH_SHORT).show();
					} catch (NotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
					return false;
				}
			});
		 
		 handler2 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了  
             @SuppressWarnings("deprecation")  
             @Override  
             // 这里notification.setLatestEventInfo，  
             // 设置通知标题与内容会被eclipse标志过时，  
             // 但新的方法，使用builder去设置通知的方法只能应用于android3.0以上的设备，对于android2.2的设备是无法使用的。  
             // 在现时国内有部分设备还是在android2.2的情况下，还是用这条几乎兼容所有版本安卓的“过时”方法吧！  
             public boolean handleMessage(Message msg) {  

                 Notification notification = new Notification();  
                 notification.icon = R.drawable.ic_login;// 设置通知图标为app的图标  
                 notification.flags = Notification.FLAG_AUTO_CANCEL;// 点击通知打开引用程序之后通知自动消失  
                 notification.tickerText = "您有一条新消息";// 在用户没有拉开标题栏之前，在标题栏中显示的文字  
                 notification.when = System.currentTimeMillis();// 设置发送时间  
                 notification.defaults = Notification.DEFAULT_ALL;// 设置使用默认声音、震动、闪光灯  
                 // 以下三行：在安卓设备任意环境中中，如果点击信息则打开MainActivity  
                 Intent intent = new Intent(getApplicationContext(),  
                         MainActivity.class);  
                 PendingIntent pendingIntent = PendingIntent  
                         .getActivity(getApplicationContext(), 0,  
                                 intent, 0);  
                 notification.setLatestEventInfo(  
                         getApplicationContext(), "提示：", "您收到"+recmess.getSendname()+"发来的新消息！",pendingIntent);  
                                  
                       
                 notificationManager.notify(  
                         1, notification);// 要求通知管理器发送这条通知，其中第一个参数是通知在系统的id  
                 return false;  
             }  
         });  
		  return START_STICKY;
	}

}
